package global

import (
	"context"
	"fmt"
	mqtt "github.com/eclipse/paho.mqtt.golang"
	"github.com/mark3labs/mcp-go/server"
	"sync"

	"github.com/gin-gonic/gin"
	"github.com/qiniu/qmgo"

	"github.com/flipped-aurora/gin-vue-admin/server/utils/timer"
	"github.com/songzhibin97/gkit/cache/local_cache"

	"golang.org/x/sync/singleflight"

	"go.uber.org/zap"

	"github.com/flipped-aurora/gin-vue-admin/server/config"
	"github.com/redis/go-redis/v9"
	"github.com/spf13/viper"
	"gorm.io/gorm"
)

var (
	GVA_DB        *gorm.DB
	GVA_DBList    map[string]*gorm.DB
	GVA_REDIS     redis.UniversalClient
	GVA_REDISList map[string]redis.UniversalClient
	GVA_MONGO     *qmgo.QmgoClient
	GVA_CONFIG    config.Server
	GVA_VP        *viper.Viper
	// GVA_LOG    *oplogging.Logger
	GVA_LOG                  *zap.Logger
	GVA_Timer                timer.Timer = timer.NewTimerTask()
	GVA_Concurrency_Control              = &singleflight.Group{}
	GVA_ROUTERS              gin.RoutesInfo
	GVA_ACTIVE_DBNAME        *string
	GVA_MCP_SERVER           *server.MCPServer
	BlackCache               local_cache.Cache
	lock                     sync.RWMutex
	GVA_MQTT_CLIENT          mqtt.Client // 新增MQTT客户端全局变量
	GVA_MQTT_MESSAGE_MANAGER interface{} // 新增MQTT消息管理器全局变量，初始化时赋值为*system.MQTTMessageManager，避免循环依赖
	RDB                      *redis.Client
)

// GetGlobalDBByDBName 通过名称获取db list中的db
func GetGlobalDBByDBName(dbname string) *gorm.DB {
	lock.RLock()
	defer lock.RUnlock()
	return GVA_DBList[dbname]
}

// MustGetGlobalDBByDBName 通过名称获取db 如果不存在则panic
func MustGetGlobalDBByDBName(dbname string) *gorm.DB {
	lock.RLock()
	defer lock.RUnlock()
	db, ok := GVA_DBList[dbname]
	if !ok || db == nil {
		panic("db no init")
	}
	return db
}

func GetRedis(name string) redis.UniversalClient {
	redis, ok := GVA_REDISList[name]
	if !ok || redis == nil {
		panic(fmt.Sprintf("redis `%s` no init", name))
	}
	return redis
}
func InitRedis() {
	rdb := redis.NewClient(&redis.Options{
		Addr:     "14.103.243.155:6379",              // Redis 地址
		Password: "8b7b2201c07309906f80c4af2fdd6b54", // 密码（无则空）
		DB:       0,                                  // 数据库
	})
	// 测试连接（可选但推荐）
	_, err := rdb.Ping(context.Background()).Result()
	if err != nil {
		panic("Redis 连接失败: " + err.Error())
	}
	GVA_REDIS = rdb
}
